package org.ruixue.service;

import cn.rkylin.oms.common.dto.DBLog;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.ruixue.dao.*;
import org.ruixue.dao.oms.EcTradeMapper;
import org.ruixue.dao.oms.LgstMapper;
import org.ruixue.dao.oms.ShiporderMapper;
import org.ruixue.dao.oms.ShopMapper;
import org.ruixue.dao.oms.SysOrderMapper;
import org.ruixue.dao.yshop.StoreOrderMapper;
import org.ruixue.entity.oms.EcTrade;
import org.ruixue.entity.oms.Lgst;
import org.ruixue.entity.oms.Shiporder;
import org.ruixue.entity.oms.Shop;
import org.ruixue.entity.oms.SysOrder;
import org.ruixue.entity.yshop.StoreOrder;
import org.ruixue.entity.yshop.StoreOrderExample;
import org.ruixue.request.ConsignShipOrderRequest;
import org.ruixue.response.BaseResponse;
import org.ruixue.util.DateUtil;
import org.ruixue.util.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.apache.commons.lang3.StringUtils.isBlank;

@Service("shipService")
public class ShipService {

    @Value("${oms.address}")
    String omsUrl;

    @Autowired
    LogUtil logUtil;

    @Autowired
    ShopMapper shopMapper;

    @Autowired
    ShiporderMapper shiporderMapper;

    @Autowired
    EcTradeMapper ecTradeMapper;

    @Autowired
    SysOrderMapper sysOrderMapper;
    
    @Autowired
    LgstMapper lgstMapper;
    
    @Autowired
    StoreOrderMapper storeOrderMapper;

    /**
     * 平台发货 按店铺
     *
     * @param shopId
     * @return
     */
    public BaseResponse consignSuningShipOrder(String shopId) throws Exception {
        if (isBlank(shopId)) {
            return new BaseResponse("false", "shopId is null");
        }
        Shop shop = shopMapper.selectByPrimaryKeyShop(shopId);
        if (shop == null) {
            return new BaseResponse("false", "shop is null");
        }

        List<Shiporder> lstShiporder = shiporderMapper.selectByShopShipOrderConsign(shop);
        for (Shiporder shiporder : lstShiporder) {
            // 如果是合并的订单
            if (shiporder.getTradeCode().indexOf(",") != -1) {
                String[] tradeCodeArrs = shiporder.getTradeCode().split(",");
                for (String tradeCode : tradeCodeArrs) {
                    // 平台发货
                    consignSuningShipOrder(tradeCode, shop, shiporder);

                }
                continue;
            }
            // 如果非合并的订单
            // 平台发货
            consignSuningShipOrder(shiporder.getTradeCode(), shop, shiporder);
        }
        return new BaseResponse();
    }

    /**
     * 平台发货 按店铺
     *
     * @param ecTradeCode
     * @param shop
     * @param shiporder
     * @return
     * @throws ParseException
     */
    private BaseResponse consignSuningShipOrder(String ecTradeCode, Shop shop, Shiporder shiporder) throws Exception {

        EcTrade ecTradeSelect = new EcTrade();
        ecTradeSelect.setShopId(shop.getShopId());
        ecTradeSelect.setEcTradeCode(ecTradeCode);

        EcTrade ecTradeModel = ecTradeMapper.selectByPrimaryKeyEcTrade(ecTradeSelect);
        if (ecTradeModel == null) {
            return new BaseResponse("false", "ecTradeModel is null");
        }

        // 判断平台订单状态
        // EB_WAIT_BUYER_PAY(等待买家付款)
        // EB_WAIT_SELLER_SEND(等待卖家发货,即:买家已付款) EB_TRADE_PARTIALLY_SEND(交易部分发货)
        // EB_TRADE_ALL_SEND(交易全部发货) EB_TRADE_FINISHED(交易成功)
        // EB_TRADE_CANCELED(交易取消)
        if ("EC_TRADE_FINISHED".equals(ecTradeModel.getEcTradeStatus())
                || "EC_TRADE_CANCELED".equals(ecTradeModel.getEcTradeStatus())) {
            // 保存数据
            consignSuningShipOrderSaveData(shop, shiporder);
            return new BaseResponse();
        }

        ConsignShipOrderRequest consignShipOrderRequest = new ConsignShipOrderRequest();
        consignShipOrderRequest.setEcTradeCode(ecTradeCode);
        consignShipOrderRequest.setLgstCode(shiporder.getLgstCode());
        consignShipOrderRequest.setLgstNo(shiporder.getLgstNo());

        // 调用平台发货接口
        BaseResponse baseResponse = this.consignSuningShipOrder(shop.getShopId(), consignShipOrderRequest);
        if (baseResponse.getSuccess().equals("false")) {
            //记录日志发货单
            logUtil.info(new DBLog(shiporder.getShiporderCode(), "consignSuningShipOrder", "consignSuningShipOrder",
                    DateUtil.getCurrentDateStr() + "  发货单: 系统自动平台发货任务, 发货失败: " + baseResponse.getMsg()));
            return baseResponse;
        }

        //  保存数据
        consignSuningShipOrderSaveData(shop, shiporder);
        return new BaseResponse();
    }


    /**
     * 平台发货 保存数据
     *
     * @param shop
     * @param shiporder
     * @param isUpdateSysOrder
     * @throws ParseException
     */
    private void consignSuningShipOrderSaveData(Shop shop, Shiporder shiporder) throws ParseException {

        // 更新发货单
        Shiporder shiporderUpdate = new Shiporder();
        shiporderUpdate.setShiporderCode(shiporder.getShiporderCode());
        shiporderUpdate.setShopId(shop.getShopId());
        shiporderUpdate.setConsignStatus("y");
        shiporderUpdate.setConsignTime(new Date());
        shiporderMapper.updateByPrimaryKeySelectiveShiporder(shiporderUpdate);

        // 更新订单
        SysOrder sysOrderUpdate = new SysOrder();
        sysOrderUpdate.setTradeCode(shiporder.getTradeCode());
        sysOrderUpdate.setShopId(shop.getShopId());
        sysOrderUpdate.setConsignTime(new Date());
        sysOrderMapper.updateByPrimaryKeySelectiveSysOrder(sysOrderUpdate);

        // 记录日志发货单
        logUtil.info(new DBLog(shiporder.getShiporderCode(), "", "consignSuningShipOrderSaveData",
                DateUtil.getCurrentDateStr() + "  发货单: 系统自动平台发货任务, 发货成功!"));
    }

    /**
     * 平台发货
     *
     * @param shopId
     * @param consignShipOrderRequest
     * @return
     */
    public BaseResponse consignSuningShipOrder(String shopId, ConsignShipOrderRequest consignShipOrderRequest) throws Exception {

        if (StringUtils.isBlank(shopId)) {
            return new BaseResponse("false", "shopId is null");
        }
        Shop shop = shopMapper.selectByPrimaryKeyShop(shopId);
        if (shop == null) {
            return new BaseResponse("false", "shop is null");
        }

        Lgst lgst = new Lgst();
        lgst.setPrjId(shop.getPrjId());
        lgst.setLgstCode(consignShipOrderRequest.getLgstCode());
        Lgst lgstModel = lgstMapper.selectByPrimaryKeyLgst(lgst);
        if (lgstModel == null) {
            return new BaseResponse("false", "lgstModel is null");
        }

        // 物流公司名称
        String lgstName = getExpressName(lgstModel.getLgstName());
        
        // 查询商城订单
        StoreOrderExample storeOrderExample=new StoreOrderExample();
        storeOrderExample.createCriteria().andOrderIdEqualTo(consignShipOrderRequest.getEcTradeCode());
        List<StoreOrder> storeOrderList=storeOrderMapper.selectByExample(storeOrderExample);
        if(storeOrderList.size()>0) {
        	StoreOrder storeOrder=storeOrderList.get(0);
        	// 订单状态
        	storeOrder.setStatus((byte) 1);
        	// 物流公司
        	storeOrder.setDeliverySn(lgstName);
        	// 物流单号                         
        	storeOrder.setDeliveryId(consignShipOrderRequest.getLgstNo());
        	storeOrderMapper.updateByPrimaryKeySelective(storeOrder);
        }
        return new BaseResponse();
    }

    /**
     * 获取物流公司名称
     *
     * @param expressName
     * @return
     * @throws Exception
     */
    private String getExpressName(String expressName) {

        expressName = expressName.replace("快运", "");
        expressName = expressName.replace("速递", "");
        expressName = expressName.replace("快递", "");
        expressName = expressName.replace("物流", "");
        expressName = expressName.replace("E物流", "");
        expressName = expressName.replace("速运", "");
        expressName = expressName.replace("邮政", "");
        expressName = expressName.replace("广东", "");
        expressName = expressName.replace("经济", "");
        expressName = expressName.replace("百世", "");
        return expressName;

    }
}
